express = require 'express'
http = require 'http'
path = require 'path'
fs = require 'fs'

app = express()

app.set 'port', process.env.PORT ? 3000		#设置服务端口

#express 配置 begin ---------------------
app.use express.urlencoded()
app.use express.json()
app.use express.methodOverride()
if 'development' is app.get 'env'
  app.use express.errorHandler()
#express 配置 end =======================

app.use (err,req,res,next) ->
	console.log '出现异常'
	console.error err.stack
	res.send 500,'{"head":{"response_code":"999999", "response_desc":"未知系统异常"}"}'

app.use (req,res,next) ->
	begin = new Date()
	console.log '%s -> %s', req.method, req.url
	next()
	console.log('运行时间：' + (new Date().getTime() - begin.getTime()))

app.all '/Spika-Server/wwwroot/api/auth',(req,res)->
	console.log req.body
	throw new Error('123')
	res.end '{"_id":"11","name":"lzt","about":"","email":"lzt@test.com","password":"4297f44b13955235245b2497399d7a93","online_status":"online","max_contact_count":20,"max_favorite_count":10,"token":"pEVAD5A7DCfhfdwNOltTcXJhIymbe4Xj4ZDU5iYF","token_timestamp":"1397880132","last_login":1397880132,"birthday":0,"gender":"","avatar_file_id":"tTp9twB1aQNZ10aRZzt11395627953","avatar_thumb_file_id":"EVhGPd1QcA2ZlLICnWTF1395627953","ios_push_token":null,"android_push_token":"APA91bGLWmMrhR6XGvV2a2rEDowDF_tauMv9DAPqQoEVQOQh6pm1JLtaapvA9ZHC2unsGSTvlI0bK2IGyWKI1edsaSUTi-Ragh9X0F5k5wO8--Ap33HVStahAn8I0ZeSnjKOX2nHscFtaSQ6HYacew6rO50aAviq5Q","created":1395453405,"modified":1395627953,"contacts":[],"favorite_groups":[],"type":"user","_rev":"tmprev"}'

app.all '/Spika-Server/wwwroot/api/activitySummary',(req,res)->
	console.log req.param 'user'
	res.end '{"total_rows":1,"offset":0,"rows":[{"id":"11","key":"11","value":{"_id":"11","_rev":"tmprev","type":"activity_summary","user_id":"11","recent_activity":{"direct_messages":{"name":"Chat activity","target_type":"user","notifications":[{"target_id":"12","count":"0","messages":[],"lastupdate":1395652840}]}}}}]}'

app.all '/sendGet',(req,res)->
	options = 
	    host: 'localhost',
	    path: '/jtgzfw/ajax.do',
	    method: 'POST',
	    port : 8080
	    headers: 
	        'Accept': 'text/html'
	        'Content-Type' : 'application/x-www-form-urlencoded'
	        'Content-Length' : 30
    
	request = http.request options,(response)->
		response.setEncoding 'utf-8'
		response.on 'data',(data)->
			res.end data
	request.write('name=lianzt&password=asdfadsf\n')
	request.end()

app.all '/demo/test', (req,res) ->
   res.end 'hello ' + req.body.say

#启动服务
http.createServer(app).listen app.get('port'), ->
  console.log "服务启动完成：server listening on port 3000"